package com.tduck.cloud.datav.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tduck.cloud.common.util.Result;
import com.tduck.cloud.common.util.SecurityUtils;
import com.tduck.cloud.common.util.ShortIdUtils;
import com.tduck.cloud.datav.entity.ScreenEntity;
import com.tduck.cloud.datav.request.ScreenRequest;
import com.tduck.cloud.datav.service.ScreenService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/**
 * 数据大屏管理
 *
 * @author tduck-gen
 * @since 2022-02-20 13:44:13
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/datav/screen")
public class ScreenController {
    private final ScreenService screenService;

    /**
     * 查询数据大屏用户项目列表
     */
    @GetMapping("/page")
    public Result<Page<ScreenEntity>> queryPage(Page<ScreenEntity> page, ScreenEntity screenEntity) {
        screenEntity.setUserId(SecurityUtils.getUserId());
        QueryWrapper<ScreenEntity> queryWrapper = Wrappers.<ScreenEntity>query()
                .eq(StrUtil.toUnderlineCase(ScreenEntity.Fields.userId), SecurityUtils.getUserId())
                .like(StrUtil.isNotBlank(screenEntity.getName()), StrUtil.toUnderlineCase(ScreenEntity.Fields.name), screenEntity.getName())
                .eq(Objects.nonNull(screenEntity.getGroupId()), StrUtil.toUnderlineCase(ScreenEntity.Fields.groupId), screenEntity.getGroupId())
                .orderByDesc(StrUtil.isNotBlank(screenEntity.getSortColumn()), StrUtil.toUnderlineCase(screenEntity.getSortColumn()));
        Page<ScreenEntity> pageResult = screenService.page(page, queryWrapper);
        return Result.success(pageResult);
    }

    /**
     * 获取数据大屏用户项目详细信息
     */
    @GetMapping(value = "/{id}")
    public Result<ScreenEntity> getInfo(@PathVariable("id") Long id) {
        return Result.success(screenService.getById(id));
    }

    /**
     * 获取数据大屏用户项目详细信息
     */
    @GetMapping(value = "/key/{key}")
    public Result<ScreenEntity> getByKey(@PathVariable("key") String key) {
        return Result.success(screenService.getOne(Wrappers.<ScreenEntity>lambdaQuery().eq(ScreenEntity::getShareKey, key)));
    }

    /**
     * 保存数据大屏用户项目
     */
    @PostMapping("save")
    public Result<ScreenEntity> save(@RequestBody ScreenEntity screenEntity) {
        screenEntity.setUserId(SecurityUtils.getUserId());
        if (ObjUtil.isNull(screenEntity.getId()) && ObjUtil.isNull(screenEntity.getShareKey())) {
            screenEntity.setShareKey(ShortIdUtils.genId());
        }
        boolean save = screenService.saveOrUpdate(screenEntity, Wrappers.<ScreenEntity>lambdaQuery().eq(ScreenEntity::getShareKey, screenEntity.getShareKey()));
        return Result.success(screenEntity);
    }

    /**
     * 修改数据大屏用户项目
     */
    @PostMapping("update")
    public Result<ScreenEntity> update(@RequestBody ScreenEntity screenEntity) {
        screenService.update(screenEntity, Wrappers.<ScreenEntity>lambdaQuery().eq(ScreenEntity::getShareKey, screenEntity.getShareKey()));
        return Result.success(screenEntity);
    }


    /**
     * 删除数据大屏用户项目
     */
    @PostMapping("/delete/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(screenService.removeById(id));
    }

    /**
     * 复制数据大屏用户项目
     */
    @PostMapping(value = "/{id}/copy")
    public Result<Boolean> copy(@PathVariable("id") Long id) {
        ScreenEntity projectEntity = screenService.getById(id);
        projectEntity.setName(projectEntity.getName() + "Copy");
        projectEntity.setId(null);
        projectEntity.setShareKey(ShortIdUtils.genId());
        screenService.save(projectEntity);
        return Result.success(true);
    }


    /**
     * 获取发布信息
     *
     * @param screenKey 大屏Id
     * @return 发布信息
     */
    @GetMapping("/{screenKey}/publish")
    public Result<Map<Object, Object>> getPublishScreenInfo(@PathVariable String screenKey) {
        ScreenEntity screen = screenService.getOne(Wrappers.<ScreenEntity>lambdaQuery().eq(ScreenEntity::getShareKey, screenKey));
        if (!Objects.equals(SecurityUtils.getUserId(), screen.getUserId())) {
            return Result.success();
        }
        Map<Object, Object> result = MapUtil.newHashMap();
        result.put(ScreenEntity.Fields.id, screen.getId());
        result.put(ScreenEntity.Fields.status, screen.getStatus());
        result.put(ScreenEntity.Fields.password, screen.getPassword());
        return Result.success(result);
    }

    /**
     * 获取是否设置密码
     */
    @GetMapping("/hasPassword")
    public Result<Boolean> hasPassword(@RequestParam String shareKey) {
        ScreenEntity screenEntity = screenService.getOne(Wrappers.<ScreenEntity>lambdaQuery().eq(ScreenEntity::getShareKey, shareKey));
        try {
            if (screenEntity.getUserId().equals(SecurityUtils.getUserId())) {
                return Result.success(false);
            }
        } catch (Exception ignored) {

        }
        return Result.success(StrUtil.isNotBlank(screenEntity.getPassword()));
    }


    /**
     * 检查密码是否正确
     */
    @PostMapping("/checkPassword")
    public Result<Boolean> checkPassword(@RequestBody ScreenRequest.CheckPassword checkRequest) {
        ScreenEntity dashboardPage = screenService.getOne(Wrappers.<ScreenEntity>lambdaQuery().eq(ScreenEntity::getShareKey, checkRequest.getShareKey()));
        return Result.success(Objects.equals(dashboardPage.getPassword(), checkRequest.getPassword()));
    }


    /**
     * 查看大屏
     */
    @GetMapping("/view/{screenKey}")
    public Result<ScreenEntity> viewScreen(@PathVariable String screenKey) {
        ScreenEntity screenEntity = screenService.getOne(Wrappers.<ScreenEntity>lambdaQuery().eq(ScreenEntity::getShareKey, screenKey));
        try {
            if (screenEntity.getUserId().equals(SecurityUtils.getUserId())) {
                return Result.success(screenEntity);
            }
        } catch (Exception ignored) {
        }
        if (Objects.equals(screenEntity.getStatus(), 1)) {
            return Result.success(screenEntity);
        }
        return Result.success(null);
    }

}
